package com.mlming.simpledb.backend.dm.page;

import com.mlming.simpledb.backend.dm.pageCache.PageCache;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PageImpl implements Page {
    private int pageNumber; // 页号
    private Lock lock; // 锁
    private boolean dirty; // 脏页标识
    private byte[] data; // 实际字节数据
    // 用于实现页面缓存的类(通过继承之前实现的通用的引用计数法缓存框架)
    // 注意: 只有当该Page被缓存了, 才需要有这个参数,
    //      因为这个参数的逻辑含义应该是: 该页面被pc缓存了,可以通过pc来实现对该页面的缓存相关操
    private PageCache pc;

    public PageImpl(int pageNumber, byte[] data, PageCache pc) {
        this.pageNumber = pageNumber;
        this.data = data;
        this.pc = pc;
        lock = new ReentrantLock();
    }

    @Override
    public void lock() {
        lock.lock();
    }

    @Override
    public void unlock() {
        lock.unlock();
    }

    @Override
    public void release() {
        pc.release(this);
    }

    @Override
    public void setDirty(boolean dirty) {
        this.dirty = dirty;
    }

    @Override
    public boolean isDirty() {
        return this.dirty;
    }

    @Override
    public int getPageNumber() {
        return this.pageNumber;
    }

    @Override
    public byte[] getData() {
        return this.data;
    }
}
